<?php
class Cp_NewsController extends Pidguin_Controller_Cp_Action
{
	public function indexAction()
	{
		$this->view->news = Model_News::getInstance()->fetchAll();
	}
	
	public function createAction()
	{
		$this->view->groups = Model_Groups::getInstance()->fetchAll();
	}
	
	public function createSaveAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('title')) {
			throw new Zend_Controller_Action_Exception('Title is not set');
		}
		
		if (!preg_match('/[a-zа-я0-9_\s\:\;\"\'\,\?\!\(\)\+\*\=\-\.]*/i', $this->_getParam('title'))) {
			throw new Zend_Controller_Action_Exception('Title incorrect');
		}
		
		if (!$this->_getParam('text')) {
			throw new Zend_Controller_Action_Exception('Text is not set');
		}
		
		$letters = array(
			"а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d", "е" => "e",
			"ё" => "e", "ж" => "zh", "з" => "z", "и" => "i", "й" => "j", "к" => "k",
            "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p", "р" => "r",
            "с" => "s", "т" => "t", "у" => "u", "ф" => "f", "х" => "h", "ц" => "c",
            "ч" => "ch", "ш" => "sh", "щ" => "sh", "ы" => "i", "ь" => "", "ъ" => "",
            "э" => "e", "ю" => "yu", "я" => "ya",
			"А" => "A", "Б" => "B", "В" => "V", "Г" => "G", "Д" => "D", "Е" => "E",
			"Ё" => "E", "Ж" => "ZH", "З" => "Z", "И" => "I", "Й" => "J", "К" => "K",
            "Л" => "L", "М" => "M", "Н" => "N", "О" => "O", "П" => "P", "Р" => "R",
            "С" => "S", "Т" => "T", "У" => "U", "Ф" => "F", "Х" => "H", "Ц" => "C",
            "Ч" => "CH", "Ш" => "SH", "Щ" => "SH", "Ы" => "I", "Ь" => "", "Ъ" => "",
            "Э" => "E", "Ю" => "YU", "Я" => "YA", " " => "_"
            
		);
		$_fvalue = new Zend_Filter_Alnum();
		$_fvalue->setAllowWhiteSpace(true);
		$value = $_fvalue->filter($this->_getParam('title'));
		foreach($letters as $letterVal => $letterKey) {
			$value = str_replace($letterVal, $letterKey, $value);
		}
		
		$value = strtolower($value);
		
		// ищем новость с похожим ключем url
		$select = Model_News::getInstance()->select();
		$select->where(
			Model_News::getDefaultAdapter()->quoteInto('url_key = ?', $value)
		);
		$nr = Model_News::getInstance()->fetchRow($select);
		
		if ($nr) {
			$value = $value . '_' . substr(time() , 4);
		}
		
		$nr = Model_News::getInstance()->createRow();
		$nr->title = $this->_getParam('title');
		$nr->url_key = $value;
		$nr->content = $this->_getParam('text');
		$nr->author_id = Pidguin_Client::getInstance()->getClient()->user->id;
		$nr->created = date('Y-m-d H:i:s');		
		$nr->save();
		
		$cacheManager = Zend_Registry::get('cache');
		$cache = $cacheManager->getCache('file');
		$cache->remove('Pidguin_DB_News');
		
		$attachs = $this->_getParam('attachments');
		if (count($attachs) > 0) {
			$_am = Model_Attachments::getInstance();
			foreach ($attachs as $attach) {
				if (!preg_match('/^[0-9]*$/', $attach)) {
					continue;
				}
				$_ar = $_am->fetchRow($_am->select()->where('id = ?', $attach));
				if (!$_ar) {
					continue;
				}
				$afnr = Model_AttachmentsForNews::getInstance()->createRow();
				$afnr->news_id = $nr->id;
				$afnr->attachment_id = $attach;
				$afnr->save();
			}
		}
		
		if (count($this->_getParam('groups')) > 0) {				
			foreach ($this->_getParam('groups') as $groupId) {
				$gr = Model_NewsGroup::getInstance()->createRow();
				$gr->news_id = $nr->id;
				$gr->group_id = $groupId;
				$gr->save();
			}
		}
		
		$this->_helper->json(array('status' => 'ok'));
	}
	
	public function deleteAction()
	{
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('News id is not set');
		}
	
		$m = Model_News::getInstance();
		$select = $m->select()->where(Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $m->fetchRow($select);
		if (!$row) {
			throw new Zend_Controller_Action_Exception('News not found');
		}
		$row->delete();
		$cacheManager = Zend_Registry::get('cache');
		$cache = $cacheManager->getCache('file');
		$cache->remove('Pidguin_DB_News');
		$this->_redirect('/cp/news');
	}
	
	public function editAction()
	{
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('News ID is not set');
		}
		 
		$m = Model_News::getInstance();
		$select = $m->select()->where(Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $m->fetchRow($select);
		 
		if (!$row) {
			throw new Zend_Controller_Action_Exception('News not found');
		}
		
		$_inGroups = $row->findDependentRowset('Model_NewsGroup');
		$inGroups = array();
		if (count($_inGroups)) {
			foreach ($_inGroups as $group) {
				$_r = $group->findParentRow('Model_Groups');
				$inGroups[] = array('groupId' => $_r->id);
			}
		}
		
		$_attachments = $row->findDependentRowset('Model_AttachmentsForNews');
	    $attachments = array();
	    if (count($_attachments)) {
	        foreach ($_attachments as $attachment) {
	            $_a = $attachment->findParentRow('Model_Attachments');
	            $attachments[] = array('url' => $_a->url, 'id' => $_a->id, 'type' => $_a->type);
	        }
	    }
		
		$this->view->news = $row;
		$this->view->groups = Model_Groups::getInstance()->fetchAll();
		$this->view->attachments = Zend_Json::encode($attachments);
		$this->view->inGroups = Zend_Json::encode($inGroups);
		$this->view->comments = $row->findDependentRowset('Model_NewsComments');
	}
	
	public function editSaveAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('News ID is not set');
		}
		
		if (!$this->_getParam('title')) {
			throw new Zend_Controller_Action_Exception('Title is not set');
		}
		
		if (!preg_match('/[a-zа-я0-9_\s\:\;\"\'\,\?\!\(\)\+\*\=\-\.]*/i', $this->_getParam('title'))) {
			throw new Zend_Controller_Action_Exception('Title incorrect');
		}
		
		if (!$this->_getParam('text')) {
			throw new Zend_Controller_Action_Exception('Text is not set');
		}
		
		$letters = array(
			"а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d", "е" => "e",
			"ё" => "e", "ж" => "zh", "з" => "z", "и" => "i", "й" => "j", "к" => "k",
            "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p", "р" => "r",
            "с" => "s", "т" => "t", "у" => "u", "ф" => "f", "х" => "h", "ц" => "c",
            "ч" => "ch", "ш" => "sh", "щ" => "sh", "ы" => "i", "ь" => "", "ъ" => "",
            "э" => "e", "ю" => "yu", "я" => "ya",
			"А" => "A", "Б" => "B", "В" => "V", "Г" => "G", "Д" => "D", "Е" => "E",
			"Ё" => "E", "Ж" => "ZH", "З" => "Z", "И" => "I", "Й" => "J", "К" => "K",
            "Л" => "L", "М" => "M", "Н" => "N", "О" => "O", "П" => "P", "Р" => "R",
            "С" => "S", "Т" => "T", "У" => "U", "Ф" => "F", "Х" => "H", "Ц" => "C",
            "Ч" => "CH", "Ш" => "SH", "Щ" => "SH", "Ы" => "I", "Ь" => "", "Ъ" => "",
            "Э" => "E", "Ю" => "YU", "Я" => "YA", " " => "_"
            
		);
		$_fvalue = new Zend_Filter_Alnum();
		$_fvalue->setAllowWhiteSpace(true);
		$value = $_fvalue->filter($this->_getParam('title'));
		foreach($letters as $letterVal => $letterKey) {
			$value = str_replace($letterVal, $letterKey, $value);
		}
		
		$value = strtolower($value);
		
		$model = Model_News::getInstance();
		$select = $model->select()->where(Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id')));
		$row = $model->fetchRow($select);
		
		if (!$row) {
			throw new Zend_Controller_Action_Exception('News not found');
		}
		
		$row->title = $this->_getParam('title');
		$row->url_key = $value;
		$row->content = $this->_getParam('text');
		$row->modified = date('Y-m-d H:i:s');
		$row->save();
		$cacheManager = Zend_Registry::get('cache');
		$cache = $cacheManager->getCache('file');
		$cache->remove('Pidguin_DB_News');
		$groupsUser = $row->findDependentRowset('Model_NewsGroup');
		if (count($groupsUser)) {
			foreach ($groupsUser as $userGroup) {
				$userGroup->delete();
			}
		}
		
		if (count($this->_getParam('groups')) > 0) {
		    foreach ($this->_getParam('groups') as $groupId) {
			    $gr = Model_NewsGroup::getInstance()->createRow();
			    $gr->news_id = $row->id;
			    $gr->group_id = $groupId;
			    $gr->save();
		    }
		}
		
		$attachs = $this->_getParam('attachments');
		if (count($attachs) > 0) {
			$_am = Model_Attachments::getInstance();
			foreach ($attachs as $attach) {
				if (!preg_match('/^[0-9]*$/', $attach)) {
					continue;
				}
				$_ar = $_am->fetchRow($_am->select()->where('id = ?', $attach));
				if (!$_ar) {
					continue;
				}
				$j = $_ar->findDependentRowset('Model_AttachmentsForNews', 'Attachment');
				if (count($j) > 0) continue;
				$afpr = Model_AttachmentsForNews::getInstance()->createRow();
				$afpr->news_id = $row->id;
				$afpr->attachment_id = $attach;
				$afpr->save();
			}
		}
		$this->_helper->json(array('status' => 'ok'));
	}
	
	public function addCommentAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('News ID is not set');
		}
		
		if (!$this->_getParam('text')) {
			throw new Zend_Controller_Action_Exception('Text is not set');
		}
		
		// find news
		$model = Model_News::getInstance();
		$select = $model->select()->where(
			Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id'))
		);
		$newsRow = $model->fetchRow($select);
		
		if (!$newsRow) {
			throw new Zend_Controller_Action_Exception('News not found');
		}
		
		$comment = Model_NewsComments::getInstance()->createRow();
		$comment->news_id = $newsRow->id;
		$comment->author_id = Pidguin_Client::getInstance()->getClient()->user->id;
		$comment->name = Pidguin_Client::getInstance()->getClient()->user->name;
		$comment->text = strip_tags($this->_getParam('text'), '<a><img>');
		$comment->created = date('Y-m-d H:i:s');
		$comment->save();
		$date = new Zend_Date($comment->created, false, Pidguin_Application::getInstance()->getLocale());
		$this->_helper->json(array('status' => 'ok', 'comment' => array(
			'id' => $comment->id,
			'author' => $comment->name,
			'text' => stripslashes($comment->text),
			'created' => $date->toString('dd MMMM YYYYг. в HH:mm')
		)));
	}
	
	public function deleteCommentAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('id')) {
			throw new Zend_Controller_Action_Exception('News ID is not set');
		}
		
		if (!$this->_getParam('comments')) {
			throw new Zend_Controller_Action_Exception('Comments is not set');
		}
		
		// find news
		$model = Model_News::getInstance();
		$select = $model->select()->where(
			Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('id'))
		);
		$newsRow = $model->fetchRow($select);
		
		if (!$newsRow) {
			throw new Zend_Controller_Action_Exception('News not found');
		}
		
		$comments = $this->_getParam('comments');
		if (count($comments) > 0) {
			$modelNewsComment = Model_NewsComments::getInstance();
			foreach ($comments as $comment) {
				if (!preg_match('/^[0-9]*$/', $comment)) {
					continue;
				}
				$selectNewsComment = $modelNewsComment->select();
				$selectNewsComment->where('id = ?', $comment);
				$cr = $modelNewsComment->fetchRow($selectNewsComment);
				if (!$cr) continue;
				$cr->delete();
			}
		}
			
		$this->_helper->json(array('status' => 'ok'));
	}
}
